<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\logic;



use app\common\model\Game;
use app\common\model\Member;
use app\common\model\Transfer;
use app\common\model\UserAccount;
use app\common\model\UserAccountLog;
use app\common\model\UserKingInvestment;
use app\common\model\UserLevel;
use app\common\model\Wallet;
use Think\Db;

/**
 * 可用钱包接口逻辑
 */
class AvailablePurse extends ApiBase
{





    /**
     * 用户线下充值
     */
    public function down_line_recharge($data){
        $uid=decoded_user_token($data['user_token'],'member_id');
        if(empty($data['number'])){
            return ajaxreturn(1,lang('请输入支付金额'));
        }
        if(!is_numeric($data['number']) || !is_numeric($data['paytype'])){
            return ajaxreturn(1,lang('格式不正确'));
        }
        if(empty($data['money'])){
            return ajaxreturn(1,lang('请输入充值金额'));
        }
        if(empty($data['paytype'])){
            return ajaxreturn(1,lang('请选择支付方式'));
        }
        if(empty($data['cover_id'])){
            return ajaxreturn(1,lang('请上传支付截图'));
        }
        if(empty($data['remark'])){
            return ajaxreturn(1,lang('充值随机动态码不能为空'));
        }
        if($data['paytype']==1){
          //法币充值
            if(empty($data['legal'])){
                return ajaxreturn(1,lang('请选择支付方式'));
            }
        }else{
            if(empty($data['from'])){
                return ajaxreturn(1,lang('请输入转账地址'));
            }
            if(!$paytype=$this->modelWalletRechargeType->getInfo(['currency_id'=>$data['currency_id']])){
                return ajaxreturn(1,lang('请选择支付方式'));
            }
            $data['form_wallet_id']=$data['currency_id'];
        }


        //写入充值记录
        $data['user_id']=$uid;
        $data['type']=4;
        $this->modelTransfer->setInfo($data);
        return ajaxreturn(0,lang('提交充值成功,等待审核'));
    }

    /**
     * 用户转账
     */
    public function transfer($data){
        if($this->logicApiBase->member['is_transfer']==0){
            return ajaxreturn(1,lang('您的网络异常,无法完成转账'));
        }
        $uid=decoded_user_token($data['user_token'],'member_id');
        if(empty($data['mobile'])){
            return ajaxreturn(1,lang('用户名不能为空'));
        }
        if(empty($data['number'])){
            return ajaxreturn(1,lang('请输入数量'));
        }
        if(!is_numeric($data['number'])){
            return ajaxreturn(1,lang('格式不正确'));
        }
        if(!$member=$this->modelMember->getInfo(['username'=>$data['mobile']])){
            return ajaxreturn(1,lang('账号不存在'));
        }
        if($member['is_black']==1){
            return ajaxreturn(1,lang('账号已被封号'));
        }
        if($member['id']==$uid){
            return ajaxreturn(1,lang('自己不能转给自己'));
        }
        $member1=$this->modelMember->getInfo(['username'=>$data['mobile'],'path'=>['like','%,'.$uid.',%']]);
        $user_family=explode(',',$this->logicApiBase->member['path']);
        if (empty($member1) &&  !in_array($this->logicApiBase->member['id'],$user_family)) {
            return  ajaxreturn(1,lang('该用户不是您团队成员'));
        }
        //        //验证支付密码
        $result=$this->check_password($data['pin_password']);
        switch ($result)
        {
            case 1:
                return  ajaxreturn(1,lang('您的账户操作多次密码验证不正确，如果不是您本人操作，请前往修改密码'));
                break;
            case 2:
                return  ajaxreturn(1,lang('您的密码验证错误2次，您的账户为了账户安全，已被冻结，请在30分钟后再次尝试。'));

                break;
            case 3:
                return  ajaxreturn(1,lang('您的密码验证错误1次，您还可以尝试1次！'));
                break;


        }
//        if(!empty($data['gc'])){
//            $wallet_id=3;
//        }else{
//            $wallet_id=1;
//        }
        $wallet_id=2;
        $wallet=$this->modelWallet->getInfo(['id'=>$wallet_id]);
//        if($data['number']<$wallet['transfer_min']){
//            return ajaxreturn(1,lang('转账数量最低为').$wallet['transfer_min']);
//        }
//        if($data['number']>$wallet['transfer_max']){
//            return ajaxreturn(1,lang('转账数量最高为'.$wallet['transfer_max']));
//        }
//        //转账手续费
//        $poundage_number=$data['number']*$wallet['poundage']/100;
        $total=$data['number'];


        Db::startTrans();
        $account=UserAccount::check(['wallet_id'=>$wallet['id'],'user_id'=>$uid],false);
        $account1=UserAccount::check(['wallet_id'=>$wallet['id'],'user_id'=>$member['id']],false);

        if($total>$account['balance']){
            return ajaxreturn(1,lang('注册钱包余额不足'));
        }
        try{
            //扣除用户钱包余额
            $account->balance-=$total;
            $account->save();

            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$uid,
                'number'=>$total,
                'wallet_id'=>$wallet_id,
                'remark'=>'注册钱包内转',
                'before_blance'=>$account->balance+$total,
                'after_blance'=>$account->balance,
                'is_add'=>2,
                'type'=>3
            ]);

            //收款用户进账
            $account1->balance+=$data['number'];
            $account1->save();

            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$member['id'],
                'number'=>$data['number'],
                'remark'=>'注册钱包内转',
                'wallet_id'=>$wallet_id,
                'before_blance'=>$account1->balance-$data['number'],
                'after_blance'=>$account1->balance,
                'is_add'=>1,
                'type'=>3
            ]);


            //写入转账记录
            $data['user_id']=$uid;
            $data['form_wallet_id']=$wallet_id;
            $data['uid']=$member['id'];
            $data['type']=1;
            $data['state']=1;
            $this->modelTransfer->setInfo($data);
            Db::commit();

            return ajaxreturn(0,lang('转账成功'));
        }catch (\Exception $e){
            Db::rollback();
//            return ajaxreturn(0,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }


    }
    /**
     * 转出娱乐城
     */
    public function transfer_out($data){

        //        //验证支付密码
        $result=$this->check_password($data['pin_password']);
        switch ($result)
        {
            case 1:
                return  ajaxreturn(1,lang('您的账户操作多次密码验证不正确，如果不是您本人操作，请前往修改密码'));
                break;
            case 2:
                return  ajaxreturn(1,lang('您的密码验证错误2次，您的账户为了账户安全，已被冻结，请在30分钟后再次尝试。'));

                break;
            case 3:
                return  ajaxreturn(1,lang('您的密码验证错误1次，您还可以尝试1次！'));
                break;


        }
        if(empty($data['number'])){
            return ajaxreturn(1,lang('请输入数量'));
        }
        if(!is_numeric($data['number'])){
            return ajaxreturn(1,lang('格式不正确'));
        }



        Db::startTrans();
        $account=UserAccount::check(['wallet_id'=>1,'user_id'=>$this->logicApiBase->member['id']],false);
        if($data['number']>$account['balance']){
            return ajaxreturn(1,lang('总包余额不足'));
        }



        try{
            //扣除用户钱包余额
            $account->balance-=$data['number'];
            $account->save();
            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$this->logicApiBase->member['id'],
                'number'=>$data['number'],
                'wallet_id'=>1,
                'before_blance'=>$account->balance+$data['number'],
                'after_blance'=>$account->balance,
                'is_add'=>2,
                'type'=>15
            ]);
            //写入转账记录
            $data['user_id']=$this->logicApiBase->member['id'];
            $data['type']=8;
            $data['form_wallet_id']=1;
            $data['state']=1;
            $this->modelTransfer->setInfo($data);
            //转出娱乐平台
            if(!$this->logicApiBase->member->trade_out_money($data['token'],$data['number'])){
                Db::rollback();
                return  ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
            }
            Db::commit();
            return ajaxreturn(0,lang('转出成功'));
        }catch (\Exception $e){
            Db::rollback();
//            return ajaxreturn(0,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }


    }


    /**
     * 总包转入注册钱包（报单包）
     */
    public function transfer_to_reg_wallet($data){
        $uid=$this->logicApiBase->member['id'];
        //        //验证支付密码
        $result=$this->check_password($data['pin_password']);
        switch ($result)
        {
            case 1:
                return  ajaxreturn(1,lang('您的账户操作多次密码验证不正确，如果不是您本人操作，请前往修改密码'));
                break;
            case 2:
                return  ajaxreturn(1,lang('您的密码验证错误2次，您的账户为了账户安全，已被冻结，请在30分钟后再次尝试。'));

                break;
            case 3:
                return  ajaxreturn(1,lang('您的密码验证错误1次，您还可以尝试1次！'));
                break;


        }
        if(empty($data['number'])){
            return ajaxreturn(1,lang('请输入数量'));
        }
        if(!is_numeric($data['number'])){
            return ajaxreturn(1,lang('格式不正确'));
        }
        $wallet_info=Wallet::get(1);
        //是否开启兑换
        if($wallet_info['is_exchange']!=1){
            return ajaxreturn(1,lang('暂未开启'));
        }
        $exchange_min=(int)$wallet_info['exchange_min'];
        $exchange_max=(int)$wallet_info['exchange_max'];
        $exchange_daily_limit=(int)$wallet_info['exchange_daily_limit'];

        if($exchange_min>0){
            if($wallet_info['exchange_min']>$data['number']){
                return ajaxreturn(1,lang('转入最小金额为').$exchange_min);
            }

        }
        if($exchange_max>0){
            if($wallet_info['exchange_max']<$data['number']){
                return ajaxreturn(1,lang('转入最大金额为').$exchange_max);
            }

        }
        if($wallet_info['exchange_mult']>0){
            if($data['number']%$wallet_info['exchange_mult']!=0){
                return ajaxreturn(1,lang('转入金额必须为').$wallet_info['exchange_mult'].lang('的倍数'));
            }

        }

        if($exchange_daily_limit>0){
            $total_money=UserAccountLog::where(['create_time'=>['between',[getTodayStart(),getTodayEnd()]],'user_id'=>$uid,'type'=>16,'wallet_id'=>$wallet_info['id'],'is_add'=>2])->sum('number')+0;

            if($total_money+$data['number']>$wallet_info['exchange_daily_limit']){
                return ajaxreturn(1,lang('今日转入已达到上限'));
            }

        }



        Db::startTrans();
        $account=UserAccount::check(['wallet_id'=>1,'user_id'=>$uid],false);
        $account_reg=UserAccount::check(['wallet_id'=>3,'user_id'=>$uid],false);
        if($data['number']>$account['balance']){
            return ajaxreturn(1,lang('总包余额不足'));
        }
        $poundage_number=$data['number']*$wallet_info['exchange_poundage']/100;
        try{
            //扣除用户总钱包余额
            $account->balance-=$data['number'];
            $account->save();
            //理财钱包增加
            $account_reg->balance+=$data['number']-$poundage_number;
            $account_reg->save();


            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$uid,
                'number'=>$data['number'],
                'wallet_id'=>1,
                'before_blance'=>$account->balance+$data['number'],
                'after_blance'=>$account->balance,
                'poundage_number'=>$poundage_number,
                'is_add'=>2,
                'remark'=>'总包转入理财钱包',
                'type'=>16
            ]);

            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$uid,
                'number'=>$data['number'],
                'wallet_id'=>3,
                'before_blance'=>$account_reg->balance-$data['number']+$poundage_number,
                'after_blance'=>$account_reg->balance,
                'poundage_number'=>$poundage_number,
                'is_add'=>1,
                'remark'=>'总包转入理财钱包',
                'type'=>16
            ]);
            //写入转账记录
            $data['user_id']=$uid;
            $data['type']=2;
            $data['form_wallet_id']=1;
            $data['to_wallet_id']=3;
            $data['state']=1;
            $data['money']=$data['number'];
            $data['exchange_type']=1;
            $this->modelTransfer->setInfo($data);
            Db::commit();
            return ajaxreturn(0,lang('转入成功'));
        }catch (\Exception $e){
            Db::rollback();
//            return ajaxreturn(0,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }


    }





    /**
     * 理财包转入总钱包
     */
    public function financial_to_wallet($data){
        $uid=$this->logicApiBase->member['id'];
        //        //验证支付密码
        $result=$this->check_password($data['pin_password']);
        switch ($result)
        {
            case 1:
                return  ajaxreturn(1,lang('您的账户操作多次密码验证不正确，如果不是您本人操作，请前往修改密码'));
                break;
            case 2:
                return  ajaxreturn(1,lang('您的密码验证错误2次，您的账户为了账户安全，已被冻结，请在30分钟后再次尝试。'));

                break;
            case 3:
                return  ajaxreturn(1,lang('您的密码验证错误1次，您还可以尝试1次！'));
                break;


        }
        if(empty($data['number'])){
            return ajaxreturn(1,lang('请输入数量'));
        }
        if(!is_numeric($data['number'])){
            return ajaxreturn(1,lang('格式不正确'));
        }

        $wallet_info=Wallet::get(3);
        $exchange_min=(int)$wallet_info['exchange_min'];
        $exchange_max=(int)$wallet_info['exchange_max'];
        $exchange_daily_limit=(int)$wallet_info['exchange_daily_limit'];
        //是否开启兑换
        if($wallet_info['is_exchange']!=1){
            return ajaxreturn(1,lang('暂未开启'));
        }

        if($exchange_min>0){
            if($wallet_info['exchange_min']>$data['number']){
                return ajaxreturn(1,lang('转入最小金额为').$exchange_min);
            }

        }
        if($exchange_max>0){
            if($wallet_info['exchange_max']<$data['number']){
                return ajaxreturn(1,lang('转入最大金额为').$exchange_max);
            }

        }
        if($wallet_info['exchange_mult']>0){
            if($data['number']%$wallet_info['exchange_mult']!=0){
                return ajaxreturn(1,lang('转入金额必须为').$wallet_info['exchange_mult'].lang('的倍数'));
            }

        }

        if($exchange_daily_limit>0){
            $total_money=UserAccountLog::where(['create_time'=>['between',[getTodayStart(),getTodayEnd()]],'user_id'=>$uid,'type'=>16,'wallet_id'=>$wallet_info['id'],'is_add'=>2])->sum('number')+0;

            if($total_money+$data['number']>$wallet_info['exchange_daily_limit']){
                return ajaxreturn(1,lang('今日转入已达到上限'));
            }

        }


        $poundage_number=$data['number']*$wallet_info['exchange_poundage']/100;
        Db::startTrans();
        $account=UserAccount::check(['wallet_id'=>3,'user_id'=>$uid],false);
        $account_all=UserAccount::check(['wallet_id'=>1,'user_id'=>$uid],false);
        if($account['freeze_balance']>0){
            return ajaxreturn(1,lang('必须等待交易员结束赎回冻结资金方可转回总包'));
        }
        if($data['number']>$account['balance']){
            return ajaxreturn(1,lang('理财包余额不足'));
        }
        try{

            $poundage_number=$data['number']*$poundage_number/100;
            $number=$data['number']-$poundage_number;
            //扣除用户理财包余额

            $account->balance-=$data['number'];
            $account->save();



            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$uid,
                'number'=>$data['number'],
                'wallet_id'=>$account['wallet_id'],
                'before_blance'=>$account->balance+$data['number'],
                'after_blance'=>$account->balance,
                'is_add'=>2,
                'poundage_number'=>$poundage_number,
                'remark'=>'理财包转入总包',
                'type'=>16
            ]);

            //总包余额增加

            $account_all->balance+=$number;
            $account_all->save();

            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$uid,
                'number'=>$number,
                'wallet_id'=>$account_all['wallet_id'],
                'before_blance'=>$account_all->balance-$number+$poundage_number,
                'after_blance'=>$account_all->balance,
                'is_add'=>1,
                'poundage_number'=>$poundage_number,
                'remark'=>'理财包转入总包',
                'type'=>16
            ]);


            //写入转账记录
            $data['user_id']=$uid;
            $data['type']=2;
            $data['form_wallet_id']=$account['wallet_id'];
            $data['to_wallet_id']=$account_all['wallet_id'];
            $data['state']=1;
            $data['poundage_number']= $poundage_number;
            $data['money']= $number;
            $data['exchange_type']=3;
            $this->modelTransfer->setInfo($data);
            Db::commit();
            return ajaxreturn(0,lang('转入成功'));
        }catch (\Exception $e){
            Db::rollback();
//            return ajaxreturn(0,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }


    }








    /**
     * 获取记账本列表
     */
    public function bookkeeping($data){
        $where=['user_id'=>$this->logicApiBase->member['id']];
        if(!empty($data['time_type'])){
            switch ($data['time_type']){
                case 1:
                    $where['create_time']=['between',[getTodayStart(),TIME_NOW]];
                    break;
                case 2:
                    $where['create_time']=['between',[TIME_NOW-86400,TIME_NOW]];
                    break;
                case 3:

                    $where['create_time']=['between',[TIME_NOW-86400*7,TIME_NOW]];
                    break;
                case 4:

                    $where['create_time']=['between',[TIME_NOW-86400*30,TIME_NOW]];
                    break;

            }
        }else{
            if(!empty($data['start_time']) && !empty($data['end_time']) ){
                $start_time=strtotime($data['start_time'].' 00:00:00');
                $end_time=strtotime($data['end_time'].' 23:59:59');
                $where['create_time']=['between',[$start_time,$end_time]];
            }
        }
        if(!empty($data['type'])){
           switch ($data['type']){

               case 3:

                   $where['type']=3;
                   break;
               case 4:

                   $where['type']=4;
                   break;
           }
        }else{
            $where['type']=['in',[3,4]];
        }

        $pay_list=$this->modelBonusLog->getList($where,'id,investment_id,type,pei_money,remark,serial_number,profit_ratio,king_id,user_investment_id,number,create_time','id desc');
        foreach ($pay_list as $k=>$v){
            $pay_list[$k]['list_type']=$v['type'];
        }

        return $pay_list;




    }


    /**
     * 获取红利/动态详情
     */
    public function bonus_detail($data){
        $uid=$this->logicApiBase->member['id'];

        $info=$this->modelUserAccountLog->getInfo(['id'=>$data['id'],'user_id'=>$uid]);
        if(!$info){
            return ajaxreturn(1,lang('参数错误'));
        }
        if($info['type']!=9){
            $info['level_name']=UserLevel::where(['id'=>$info['level_id']])->value('level_name');
        }


        return $info;



    }

    /**
     * 获取投资心血公式详情
     */
    public function investment_detail($data){
        $uid=$this->logicApiBase->member['id'];

        $info=$this->modelUserKingInvestment->getInfo(['id'=>$data['id'],'user_id'=>$uid]);
        if(!$info){
            return ajaxreturn(1,lang('参数错误'));
        }
        if($info['investment_type']==1){
            $info['total']=$info->investment->total;
            unset($info->investment);
        }

        return $info;



    }

    public function get_reward_config(){
       $service_fee=getConfig('service_fee');
       $level_list=UserLevel::all(['id'=>['gt',1]]);
       $dai_list=[getConfig('first_algebra'),getConfig('second_algebra'),getConfig('third_algebra'),getConfig('fouth_algebra'),getConfig('fifth_algebra')];

       return ['bonus'=>$service_fee,'level_list'=>$level_list,'dai_list'=>$dai_list,'egalitarian_reward'=>getConfig('egalitarian_reward')];
    }


















}
